package com.ruoyi.service.impl;

import com.ruoyi.domain.BaseArea;
import com.ruoyi.mapper.BaseAreaMapper;
import com.ruoyi.service.IBaseAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BaseAreaServiceImpl implements IBaseAreaService {
    @Autowired
    BaseAreaMapper baseAreaMapper;

    @Override
    public List<BaseArea> list() {
        return baseAreaMapper.selectList();
    }

    @Override
    public List<Map<String, Object>> listBaseAreaCascader() {
        List<BaseArea> list = baseAreaMapper.selectList();
        List<Map<String, Object>> data = list.stream().filter(baseArea -> baseArea.getAreaLevel() == 2)
                .map(baseArea -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("value", baseArea.getAreaId());
                    map.put("label", baseArea.getAreaName());
                    List<Map<String, Object>> twoList = list.stream().filter(baseArea1 -> baseArea1.getAreaLevel() == 3
                                    && baseArea1.getAreaParId().equals(baseArea.getAreaId()))
                            .map(baseArea1 -> {
                                Map<String, Object> twomap = new HashMap<>();
                                twomap.put("value", baseArea1.getAreaId());
                                twomap.put("label", baseArea1.getAreaName());
                                List<Map<String, Object>> threelist = list.stream().filter(baseArea2 -> baseArea2.getAreaLevel() == 4
                                        && baseArea2.getAreaParId().equals(baseArea1.getAreaId()))
                                        .map(baseArea2 -> {
                                            Map<String, Object> thrmap = new HashMap<>();
                                            thrmap.put("value", baseArea2.getAreaId());
                                            thrmap.put("label", baseArea2.getAreaName());
                                            return thrmap;
                                        }).collect(Collectors.toList());
                                if (threelist != null && threelist.size() > 0){
                                twomap.put("children", threelist);
                                }
                                return twomap;
                            }).collect(Collectors.toList());
                    map.put("children", twoList);
                    return map;
                }).collect(Collectors.toList());
        return data;
    }
}
